from datetime import datetime, timedelta


class Monitor:
    def __init__(self, threshold):
        self.threshold_dict = threshold
        # self.format_str = "%Y-%m-%d %H:%M:%S"
        self.event = {}
        self.event_time_list = []
        self.time_list = []
        self.score = 50

    def flow_change(self, data, last_data):
        flow_change_flag = 0
        # 流量变化较大
        flow = self.threshold_dict["flow"]
        up_flow = last_data["data"]["up_flow_num"] - data["data"]["up_flow_num"]
        down_flow = last_data["data"]["down_flow_num"] - data["data"]["down_flow_num"]
        # 不关注上游变化
        # if up_flow > flow * last_data["data"]["up_flow_num"]:
        #     flag = 1
        # 下游流量骤降
        if down_flow > flow * last_data["data"]["down_flow_num"]:
            flow_change_flag = 1
        # if up_flow > flow * last_data["data"]["up_flow_num"]:
        #     flow_change_flag = 0
        # 上下游流量差值
        flow_diff = max((data["data"]["up_flow_num"] - data["data"]["down_flow_num"]), 0)
        flow_diff_p = int(flow_diff / data["data"]["up_flow_num"] * 100) if data["data"]["up_flow_num"] != 0 else 100

        return flow_change_flag, flow_diff, flow_diff_p

    def car_speed(self, data, last_data, vtype="1"):
        speed_change_flag = 0
        # 小客车速度骤降
        speed = self.threshold_dict["speed"]
        if vtype not in data["data"]["type_speed_dict"].keys() or vtype not in last_data["data"]["type_speed_dict"].keys():
            return speed_change_flag, 0
        current_speed = data["data"]["type_speed_dict"][vtype]["mean_speed"]
        last_speed = last_data["data"]["type_speed_dict"][vtype]["mean_speed"]
        speed_diff = last_speed - current_speed
        if speed_diff > speed * last_speed and last_speed >= 60:
            speed_change_flag = 1
        speed_60_diff = max(int(60 - current_speed), 0)
        return speed_change_flag, speed_60_diff

    def car_slow_num(self, data, vtype="1"):
        # 小客车慢行数量过多
        # slow_num = self.threshold_dict["slow_num"]
        if vtype not in data["data"]["type_speed_dict"].keys():
            return 0
        num = data["data"]["type_speed_dict"][vtype]["slow_level_count"]
        current_slow_num = num[1] + num[2] + num[3]
        # if current_num >= slow_num:
        #     slow_num_flag = 1
        return current_slow_num

    def flow_empty(self, data):
        up_flow = data["data"]["up_flow_num"]
        down_flow = data["data"]["down_flow_num"]
        if up_flow == 0 and down_flow == 0:
            return True
        return False

    def pass_rate(self, data, vtype="1"):
        pass_rate = self.threshold_dict["pass_rate"]
        if data["info"]["info"] == "10005":
            pass_rate = 30

        if vtype is None:
            pass_rate_dict = {"pass_num": 0, "all_count": 0}
            for vtype in data["data"]["type_pass_rate_dict"].keys():
                car_pass_rate = data["data"]["type_pass_rate_dict"][vtype]
                pass_rate_dict["pass_num"] += car_pass_rate["pass"]
                pass_rate_dict["all_count"] += car_pass_rate["count"]
            current_pass_rate = int(pass_rate_dict["pass_num"] / pass_rate_dict["all_count"] * 100)
            if current_pass_rate < pass_rate:
                return 1, current_pass_rate
            else:
                return 0, current_pass_rate

        if vtype not in data["data"]["type_pass_rate_dict"].keys():
            return 0, 100
        car_pass_rate = data["data"]["type_pass_rate_dict"][vtype]

        # if car_pass_rate["count"] == 0:
        #     return 0
        current_pass_rate = int(car_pass_rate["pass"] / car_pass_rate["count"] * 100)
        if current_pass_rate < pass_rate:
            return 1, current_pass_rate
        return 0, current_pass_rate

    def interval_num(self, data):
        interval_num = int(data["info"]["dist"] * 1000 / 100.0 * data["info"]["lane_num"])
        interval_diff = max((data["data"]["interval_dict"] - interval_num), 0)
        return interval_diff

    def event_detection(self, event_time):
        flag_dict = self.event[event_time]
        block_probability = 0
        if not self.time_list:
            last_flag_dict = {}
        else:
            last_flag_dict = self.event[self.time_list[-1]] if self.time_list[-1] in self.event.keys() else {}

        if flag_dict["flow_change_flag"]:
            if flag_dict["flow_diff_p"] > 80 and flag_dict["flow_diff"] >= 5:
                block_probability += 50
            if flag_dict["pass_flag"]:
                block_probability += 50

        if flag_dict["speed_change_flag"]:
            block_probability += 50

        if last_flag_dict and last_flag_dict["block_probability"] >= self.score:
            if flag_dict["pass_flag"]:
                block_probability += 50

            if flag_dict["flow_diff_p"] > 80 and flag_dict["flow_diff"] >= 5:
                block_probability += 50
            else:
                if flag_dict["speed_60_diff"] == 0:
                    block_probability = 0

        # if flag_dict["interval_diff"] > 20:
        #     block_probability += 50

        block_probability += min(max(flag_dict["flow_diff"], 0), 20)
        block_probability += min(max(flag_dict["speed_60_diff"], 0), 30)
        block_probability += min(max((flag_dict["current_slow_num"] - 10), 0), 30)

        # if last_flag_dict:
        #     if last_flag_dict["block_probability"] >= self.score:
        #         if flag_dict["flow_empty_flag"]:
        #             block_probability += 1000

        self.event[event_time]["block_probability"] = block_probability
        if block_probability >= self.score:
            if last_flag_dict and last_flag_dict["block_probability"] >= self.score:
                self.event[event_time]["content"] = "阻断"
            else:
                self.event[event_time]["content"] = "畅通"
        else:
            self.event[event_time]["content"] = "畅通"

    def run(self, data, last_data):
        content = "畅通"
        # 结束时间 datetime类型的时间数据
        event_time = data["data"]["time"]
        if last_data is not None:
            # 流量变化标志flow_change_flag，0：正常，1：下游骤降, 上下游流量差值flow_diff
            flow_change_flag, flow_diff, flow_diff_p = self.flow_change(data, last_data)
            # speed_change_flag，0：正常，1：车速骤降，低于60的速度差值speed_60_diff
            speed_change_flag, speed_60_diff = self.car_speed(data, last_data)
            # 慢行车数量current_slow_num, 0：正常
            current_slow_num = self.car_slow_num(data)
            # 车流量为零标志flow_empty_flag，True：上下游车流量均为零，False：正常
            flow_empty_flag = self.flow_empty(data)
            # 通过率标志pass_flag，1：通过率过低，0：正常
            pass_flag, current_pass_rate = self.pass_rate(data)
            # 间隔内车数量标志interval_diff，0：正常
            interval_diff = self.interval_num(data)

            self.event[event_time] = {
                "flow_change_flag": flow_change_flag,
                "flow_diff_p": flow_diff_p,
                "flow_diff": flow_diff,
                "speed_change_flag": speed_change_flag,
                "speed_60_diff": speed_60_diff,
                "current_slow_num": current_slow_num,
                "flow_empty_flag": flow_empty_flag,
                "pass_flag": pass_flag,
                "current_pass_rate": current_pass_rate,
                "interval_diff": data["data"]["interval_dict"],
                "block_probability": 0,
                "content": "畅通"
            }

            self.event_detection(event_time)

            content = self.event[event_time]["content"]

        self.time_list.append(event_time)
        if self.event[event_time]["content"] == "畅通":
            self.event_time_list.append(event_time)

        return content, self.event[event_time]


class Congestion:
    def __init__(self):
        self.congestion = "畅通"

    def run(self, mean_speed):
        if mean_speed >= 40:
            self.congestion = "畅通"
        elif mean_speed >= 30:
            self.congestion = "轻度拥堵"
        elif mean_speed >= 20:
            self.congestion = "中度拥堵"
        else:
            self.congestion = "严重拥堵"

        return self.congestion


if __name__ == '__main__':
    print("1")
